<script setup>
import { ref,watch } from 'vue'; // 引入 Vue 3 相关的模块
import axios from 'axios';
import * as echarts from "echarts";
import {onMounted, onUnmounted} from "vue";

let pressValues = [0.3,0.5]; // 初始两个 press 值
let chartData = []; // 存储图表数据

let yAxisData = [
  0.00, 0.25, 0.50, 0.88, 1.44, 2.28, 3.55, 5.45, 7.95, 10.45, 12.95, 15.45, 17.95, 20.45, 22.95, 25.45, 27.95, 30.45, 32.95, 35.45, 37.95, 40.45, 42.95, 45.45, 47.95, 50.45, 52.95, 55.45, 57.95, 60.45, 62.95, 65.45, 67.95, 70.45, 72.95, 75.45, 76.57, 77.70, 77.79, 77.88, 77.89, 77.89, 77.89
];

let xAxisData = [
  0.00, 4.83, 9.66, 16.90, 27.77, 44.07, 68.52, 105.21, 153.54, 201.88, 250.23, 298.60, 346.98, 395.37, 443.78, 492.20, 540.63, 589.08, 637.54, 686.07, 734.69, 783.34, 831.99, 880.69, 929.48, 979.71, 1046.66, 1138.36, 2003.03, 14186.68, 29534.84, 47734.39, 69356.11, 95815.67, 130067.07, 180264.31, 215388.43, 283498.82, 296753.53, 321387.19, 321387.85, 331123.75
];

let lineChart = null;
let outerDiameter1 = ref(0);
let outerDiameter2 = ref(0);
let outerDiameter3 = ref(0);
let wallThick1 = ref(0);
let wallThick2 = ref(0);
let wallThick3 = ref(0);
// let previousPress = ref(1); // 用于存储先前的press值
let press = ref(2);
let flag = ref(0)
let baopoData = ref(null);
// const baseUrl3 = 'E:/Project/DigitalTwinPic/baopo/';
const baseUrl3 = 'http://115.24.173.26:8002/DigitalTwinPic/baopo/';

const stuNo = sessionStorage.getItem("stuNo").replace(/"/g, "");
console.log(stuNo);

const weiyiImageUrlList = ref([]);

const weiyiImageUrl = ref(null);
const yingbianImageUrl = ref(null);
const baseUrl = 'http://115.24.173.26:8002/DigitalTwinPic/baopo/';


/**
 * #3
 * @returns {Promise<void>}
 */
const getBaopoParams = async ()=>{
  await axios.post('/api/student/getBaopoParams', { stuNo: stuNo })
      .then((response) => {
        setBaopoParams(response);
      })
      .catch((error) => {
        console.error('获取参数失败', error);
      });
}

const getBaopoRandomParams = async ()=>{
  await axios.post('/api/student/getBaopoRandomParams', { stuNo: stuNo })
      .then((response) => {
        setBaopoParams(response);
      })
      .catch((error) => {
        console.error('获取参数失败', error);
      });
}

function setBaopoParams(response) {
  // 处理响应数据
  if (response.data.code === 1) {
    //   console.log(response.data);
    outerDiameter1.value=response.data.data.outerDiameter1;
    outerDiameter2.value=response.data.data.outerDiameter2;
    outerDiameter3.value=response.data.data.outerDiameter3;
    wallThick1.value=response.data.data.wallThick1;
    wallThick2.value=response.data.data.wallThick2;
    wallThick3.value=response.data.data.wallThick3;
    // console.log(wallThick3.value);
  } else {
    alert(response.data.msg);
  }
}

const compute = ()=> {
  axios.post('/api/baopo/compute', {
    stuNo: stuNo,
    outerDiameter1: outerDiameter1.value,
    outerDiameter2: outerDiameter2.value,
    outerDiameter3: outerDiameter3.value,
    wallThick1: wallThick1.value,
    wallThick2: wallThick2.value,
    wallThick3: wallThick3.value,
    stress: press.value,
    // stress: press.value,
  })
      .then((response) => {
        // 处理响应数据
        // console.log(response.data)
        if (response.data.code === 1) {
          // 在这里处理成功的情况
        } else {
          alert(response.data.msg+'1');
        }
      })
      .catch((error) => {
        console.error('获取参数失败', error);
      });
}

const compute1 = ()=>{

  var data = new FormData();
  data.append('usr', 'HBGYDX');
  data.append('pwd', '123456');
  data.append('id', '629');
  var config = {
    method: 'post',
    url: '/cgi/data.php',
    headers: {
      'Content-Type': 'multipart/form-data; boundary=--------------------------658559184002131110438280',
    },
    data : data
  };
  axios(config)
      .then(function (response) {
        var formattedPressure = parseFloat(response.data.data[0].d1).toFixed(2);
        press.value = formattedPressure;
        //  console.log(press);
      })
      .catch(function (error) {
        console.log(error);
      });

}

const getData = ()=>{
  axios.get('/api/baopo/data')
      .then((response) => {
        // 处理响应数据
        if (response.data.code === 1) {
          baopoData.value =baseUrl3 + response.data.data;
          // console.log(baopoData.value);
        } else {
          alert(response.data.msg);
        }
      })
      .catch((error) => {
        console.error('下载实验数据失败', error);
      });
}




getBaopoRandomParams().then(() => { compute() });
getData();



const downloadFile = async ()=>{
  await axios.get('/api/waiya/data')
      .then((response) => {
        // 处理响应数据
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        // 发起下载文件请求
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        // 创建一个 <a> 元素
        // 设置下载属性和文件名
        a.download = '爆破实验数据.zip';

        // 模拟点击 <a> 元素
        a.click();
      })
      .catch((error) => {
        console.error('下载实验数据失败', error);
      });
}

const startBaopo = ()=>{
  // #3 24240818
  getBaopoParams().then();
  axios.post('/api/student/stuStartBaopoExp', { stuNo: stuNo })
      .then((response) => {
        // 处理响应数据
        if (response.data.code === 1) {
          console.log(response.data);
          alert('请开始实验');
          flag.value = 1
        } else {
          alert(response.data.msg);
        }
      })
      .catch((error) => {
        console.error('开启实验失败', error);
      });
}

const weiyi = ()=> {
  axios.get('/api/baopo/weiyi')
      .then((response) => {
        // 处理响应数据
        if (response.data.code === 1) {
          weiyiImageUrl.value= baseUrl + response.data.data;
          const _weiyiImageUrl = baseUrl + response.data.data;
          if (!weiyiImageUrlList.value.includes(_weiyiImageUrl)) {
            weiyiImageUrlList.value.push(_weiyiImageUrl);
            console.log(weiyiImageUrl.value)
          }
          console.log(weiyiImageUrl.value);
        } else {
          alert(response.data.msg);
        }
      })
      .catch((error) => {
        console.error('获取图像失败', error);
      });
}

const yingbian = ()=>{
  axios.get('/api/baopo/yingbian')
      .then((response) => {
        // 处理响应数据
        if (response.data.code === 1) {
          yingbianImageUrl.value= baseUrl + response.data.data;
          console.log(yingbianImageUrl.value);
        } else {
          alert(response.data.msg);
        }
      })
      .catch((error) => {
        console.error('获取图像失败', error);
      });
}

weiyi();
yingbian();

// 找到与 press 值最接近的一组数据
function updateChartData(pressValue) {
  /*let updated = false;*/

  for (let i = 0; i < yAxisData.length; i++) {
    if (yAxisData[i] <= pressValue ) {
      const newData = { x: xAxisData[i], y: yAxisData[i], symbol: 'pin' };
      if (!chartData.some(data => data.y === newData.y && pressValue !==0)) {
        chartData.push(newData);
        /*updated = true;*/
      }
      else{
        /*删除原表格*/
        chartData.splice(0, chartData.length);
        chartData.push(newData);
      }
    }
    else {
      break; // 结束更新
    }
  }

  // return updated;
}



// 更新 press 值并重新渲染图表
function updateChart() {
  const lastPressValue = pressValues[pressValues.length - 1];
  /*  const updated = */updateChartData(lastPressValue);

  /*  if (updated) {*/
  const options = {
    grid: {
      left: '15%',

      // containLabel: true
    },
    //   title: {
    //     text: "载荷---位移曲线",
    //     left: "center",
    //   },
    xAxis: {
      type: 'value',
      name: '容积变化量（cm³）',
      nameGap: 50,
      nameLocation:'center',
      axisLabel: {
        rotate:45
      }
    },
    yAxis: {
      type: 'value',
      name: 'LOAD（MPa）',
      nameGap: 30,
      nameLocation:'center'
    },
    tooltip: {
      trigger: "axis"
    },
    series: [
      {
        type: 'line',
        smooth: true,
        data: chartData.map(data => [data.x.toFixed(6), data.y.toFixed(3)]),
      }
    ]
  };

  lineChart.setOption(options);
  /*}
  else {
    const options1 = {
      grid: {
        left: '15%',

        // containLabel: true
      },
      //   title: {
      //     text: "载荷---位移曲线",
      //     left: "center",
      //   },
      xAxis: {
        type: 'value',
        name: '容积变化量（cm³）',
        nameGap: 50,
        nameLocation:'center',
        axisLabel: {
          rotate:45
        }
      },
      yAxis: {
        type: 'value',
        name: 'LOAD（MPa）',
        nameGap: 30,
        nameLocation:'center'
      },
      tooltip: {
        trigger: "axis"
      },
      series: [
        {
          type: 'line',
          smooth: true,
          data: chartData.map(data => [data.x.toFixed(6), data.y.toFixed(3)]),
        }
      ]
    };
    lineChart.setOption(options1);
  }*/
}



// // 模拟 press 值更新，并重新渲染图表
// function simulatePressUpdate() {
//     if(flag.value){
//         const newPressValue = pressValues[pressValues.length - 1]+10; // 获取到的新的 press 值
//     //   console.log(newPressValue)
//         pressValues.push(newPressValue); // 添加新的 press 值
//     updateChart();
//     }

// }

// setInterval(simulatePressUpdate, 3000);

/**
 * #1 #2
 * 实验状态
 * @type {boolean}
 */
let expStatus = ref(false);

onMounted(() => {
  // 设置定时器，检测实验状态 #1 #2
  setInterval(() => {
    if (!expStatus.value){
      axios.get('/api/student/getBaopoStatus?stuNo=' + stuNo).then((response) => {
        // 当状态已开始时，更新引用变量
        if (response.data.data === true) {
          expStatus.value = true;
        }
      });
    }
  }, 5000)

  getBaopoParams();
  lineChart = echarts.init(document.getElementById("avi"), "purple-passion");
  updateChart();
});

onUnmounted(() => {
  lineChart.dispose;
});

const getRandomPress = () => {
  if(!flag.value){
    press.value = (Number(press.value) + 2).toFixed(2);
    if (Math.abs(+  press.value - 80) < 0.000001) {
      press.value =2
    }
  }
  else {
    compute1();
  }
};
setInterval(getRandomPress, 5000);
if(!flag.value) {
  watch(press, async (newValue, oldValue) => {
    // 执行compute()函数
    pressValues.push(newValue); // 添加新的 press 值
    updateChart();
    await compute();
    weiyi();
    yingbian();
    console.log('press值变化了，新值为：', newValue, '旧值为：', oldValue);
    //console.log(response.data.code)
  });
}
else {
  watch(press, async (newValue, oldValue) => {
    // 执行compute()函数
    pressValues.push(newValue); // 添加新的 press 值
    updateChart();
    await compute1();
    weiyi();
    yingbian();
    console.log('press值变化了，新值为：', newValue, '旧值为：', oldValue);
    //console.log(response.data.code)
  });
}
</script>


<template >
  <div class="page1 flex-base-exp">
    <div class="left-vedio">
      <div class="page-vedio flex-base-page">
        <div class="first-vedio flex-base-vedio">
          <div class="first-vedio-left" id="container">
            <div class="block text-center" m="t-4">
              <span class="demonstration">实验步骤展示</span>
              <el-carousel trigger="click" height="270px" wight="370px">
                <el-carousel-item v-for="item in 5" :key="item">
                  <!-- <h3 class="small justify-center" text="2xl">{{ item }}</h3> -->
                  <img :src="'http://115.24.173.26:8002/DigitalTwinPic/step/baopo/' + item + '.jpg'" style="width: 100%; height: 100%;">
                </el-carousel-item>
              </el-carousel>
            </div>
          </div>
        </div>
        <div class="pic1 flex-base">
          <div class="pic1-left">
            <img :src="weiyiImageUrl" class="image">
            <img v-for="img of weiyiImageUrlList" :src="img" class="image" style="width: 0; height: 0;">
          </div>
          <div class="pic1-right flex-title">
            位移云图
          </div>
        </div>
        <div class="pic2 flex-base">
          <div class="pic2-left">
            <img :src="yingbianImageUrl" class="image">
          </div>
          <div class="pic2-right flex-title">
            塑性应变云图
          </div>
        </div>
      </div>
    </div>
    <div class="right-control flex-base-right">
      <div class="right-control-top flex-base-exp">
        <div class="top-left flex-base-right">
          <div class="top-left-top flex-base-exp step">
            <div class="circle-number">1</div>得到老师上传参数实验开始
          </div>
          <div class="top-left-bottom flex-base-right">
            <table>
              <tr>
                <td>外径1：{{ outerDiameter1 }}</td>
              </tr>
              <tr>
                <td>外径2：{{ outerDiameter2 }}</td>
              </tr>
              <tr>
                <td>外径3：{{ outerDiameter3 }}</td>
              </tr>
              <tr>
                <td>壁厚1：{{ wallThick1 }}</td>
              </tr>
              <tr>
                <td>壁厚2：{{ wallThick2 }}</td>
              </tr>
              <tr>
                <td>壁厚3：{{ wallThick3 }}</td>
              </tr>
            </table>
            <button v-if="expStatus" class="top-left-bottom-button-disable" @click="startBaopo">开始实验</button>
            <button v-if="!expStatus" class="top-left-bottom-button">开始实验</button>
          </div>
        </div>
        <div class="top-right flex-base-right">
          <div class="top-right1 flex-base-exp step">
            <div class="circle-number">2</div>参数校正
          </div>
          <div class="top-right2">
            试件是材料为16Mn的厚壁圆管，弹性模量E=2×10^5，泊松比μ=0.3，屈服极限ReL=275MPa，强度极限Rm=510MPa，切线模量ET=1112.82。
          </div>
          <div class="top-right3 flex-base-exp step">
            <div class="circle-number">3</div>参数校正
          </div>
          <div class="top-right4 flex-base-exp step">
            <div class="circle-number">4</div>参数校正
          </div>
          <div class="top-right5 flex-base-right">
            爆破结束后，系统卸载，并关闭电动机及其它测量仪器。
          </div>
        </div>
      </div>
      <div class="right-control-bottom flex-base-exp">
        <div class="bottom-left flex-base-right">
          <div class="bottom-left-top" id="avi">
            <!-- <img :src="strvolImageUrl" class="image"> -->
          </div>
          <div class="bottom-left-bottom flex-base-exp">
            压力-容积变化曲线
          </div>
        </div>
        <div class="bottom-right flex-base-right">
          <div class="bottom-right-top flex-base-exp">
            实验室传感器实时显示
            <br/>
            压力：  {{ press }}  MPa
          </div>

          <div>
            <button v-if="expStatus" class="my-button2-disable" @click="downloadFile">下载实验数据</button>
            <button v-if="!expStatus" class="my-button2" disabled>下载实验数据</button>

          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<style scoped>
.demonstration {
  /* color: var(--el-text-color-secondary); */
  color: black;
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 270px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}






#divPlugin {
  position: relative;
  z-index: 1; /* 较低的层级 */
}
.plugin{
  width: 100%;
  height: 100%;
  z-index: -1;
}
.page-vedio {
  height: 100%;
  width: 526px;
}
.flex-base-page {
  display: flex;
  flex-direction: column;
}
.flex-base {
  display: flex;
  /* justify-content: center;
  align-items: center; */
  flex-direction: row;
}
.flex-title-first{
  display: flex;
  align-content: center;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  writing-mode: vertical-rl;
  font-size: 18px;
  letter-spacing: 10px;
}
.flex-title{
  display: flex;
  align-content: center;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  writing-mode: vertical-rl;
  font-size: 20px;
  letter-spacing: 5px;
}
.flex-base-vedio {
  display: flex;
  /* justify-content: center;
  align-items: center; */
}
.first-vedio {
  width: 100%;
  height: 276px;
  margin-left:25px;
  margin-top:25px;

}
.first-vedio-left {
  width:400px;
  height: 276px;
}
.first-vedio-right{
  width: 66px;
  height: 235px;
  border: 1px solid #808080;
  margin-left:7px;
  margin-top:40px;
}
.pic1 {
  width: 100%;
  height: 310px;
  margin-left:25px;
  margin-top: 30px;
}
.image {
  width: 100%; /* 图像宽度与外层盒子宽度一致 */
  height: 100%; /* 图像高度与外层盒子高度一致 */
  object-fit: cover; /* 调整图像以填充整个图像框 */
}
.pic1-left {
  width: 368px;
  height: 250px;
  border: 1px solid #808080;
}
.pic1-right {
  width: 72px;
  height: 220px;
}
.pic2 {
  width: 100%;
  height: 310px;
  margin-top:-30px;
  margin-left:25px;
}
.pic2-left {
  width: 368px;
  height: 250px;
  border: 1px solid #808080;
}
.pic2-right {
  width: 72px;
  height: 220px;
}
.flex-base-exp{
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex-base-right {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.page1 {
  width:100%;
  height: 922px;
  display: flex;
}
.left-vedio {
  width: 526px;
  height: 922px;
}
.right-control {
  width: 786px;
  height: 922px;
}
.top-left {
  width: 320px;
  height: 100%;
  margin-left: 10px;
}
.top-left-top {
  width: 100%;
  height: 60px;
}
.step {
  font-size: 24px;
  color: black;
}
.circle-number {
  display: inline;
  width: 25px; /* 圆的宽度 */
  height: 25px; /* 圆的高度 */
  border-radius: 50%; /* 使用边框半径使其变为圆形 */
  background-color:white; /* 圆的背景颜色 */
  color:black; /* 文字颜色 */
  text-align: center; /* 文字水平居中对齐 */
  line-height: 25px; /* 文字垂直居中对齐 */
  font-size: 16px; /* 文字大小 */
  border: 1px solid black;
}

.top-left-bottom {
  width: 260px;
  height: 355px;
  border: 1px solid #808080;
}
table {
  width: 180px;
  height: 240px;
  border-collapse: collapse;
}

tr {
  height: 40px; /* 设置行高为40像素 */
}
td {
  border: 1px solid #808080;
  font-size: 20px;
  /* text-align: center; */
  justify-content: center;
  color: black;
}
.top-left-bottom-button {
  width: 120px;
  height: 55px;
  border: 1px solid #808080;
  border-radius: 2px;
  font-size: 16px;
  margin-top: 20px;
  cursor: pointer;
}
.top-left-bottom-button-disable {
  width: 120px;
  height: 55px;
  border: 1px solid #808080;
  border-radius: 2px;
  font-size: 16px;
  margin-top: 20px;
  background-color: #7b7b7c;

}
.my-button2 {
  margin-top: 50px;
  width: 183px;
  height: 44px;
  border-radius: 4px;
  background-color: rgba(232, 232, 232, 1);
  color: rgba(16, 16, 16, 1);
  font-size: 22px;
  text-align: center;
  font-family: Microsoft Yahei;
  border: 1px solid rgba(187, 187, 187, 1);
}
.my-button2-disable {
  margin-top: 50px;
  width: 183px;
  height: 44px;
  border-radius: 4px;
  background-color:  #7b7b7c;
  color: rgba(16, 16, 16, 1);
  font-size: 22px;
  text-align: center;
  font-family: Microsoft Yahei;
  border: 1px solid rgba(187, 187, 187, 1);;

}
.top-right {
  width: 465px;
  height: 100%;
}
.top-right1 {
  width: 100%;
  height: 58px;
}
.top-right2 {
  width: 446px;
  height: 136px;
  font-size: 20px;
  font-weight: bold;
  border: 1px solid #808080;
  color: black;
}
.top-right3 {
  height: 66px;
  width: 100%;
}
.top-right4 {
  height: 66px;
  width: 100%;
}
.top-right5 {
  height: 112px;
  width: 356px;
  font-size: 20px;
  font-weight: bold;
  border: 1px solid #808080;
  color: black;
}
.right-control-top{
  width: 100%;
  height: 516px;
}
.right-control-bottom{
  width: 100%;
  height: 416px;
}
.bottom-left {
  flex:1;
  height: 100%;
}
.bottom-right {
  flex:1;
  height: 100%;
}
.bottom-left-top {
  width: 370px;
  height: 250px;
  border: 1px solid #808080;
}
.bottom-left-bottom {
  width: 370px;
  height: 84px;
  font-size: 16px;
  color: black;
}
.bottom-right-top{
  width: 316px;
  height:112px;
  border: 1px solid #808080;
  font-size: 18px;
  color: black;
  letter-spacing: 1px;
  align-items: center;
}

.image {
  width: 100%; /* 图像宽度与外层盒子宽度一致 */
  height: 100%; /* 图像高度与外层盒子高度一致 */
  object-fit: cover; /* 调整图像以填充整个图像框 */
}
</style>
